import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";

import { Item, Selection, Toolbar } from "devextreme-react/data-grid";
import Button from 'devextreme-react/button';
import { DevGrid } from "~/public/cpas-ui";
import { getSamplingRecordColumns } from "./tableColumnData";
import SamplingRecordPopup from "./component/samplingRecordPopup";
import { SamplingSourcePopup } from "./component/samplingSourcePopup";

import { useModel } from 'umi';
import { consts } from "./consts";
import { addOrEditOrViewSampleRecord, delSampleRecord, getAssertionTexts, getSampleRecordList } from "./tableSamplingRecordService";
import type { SampleReord } from "./typing";
import { SampleRecordEditType } from "./typing";
import { Modal } from "antd";
import { updateTableIsChecked } from "./component/samplingSampleListService";
import { getRealTableName_sampleList } from "./component/service";

/**
 * 抽样记录
 * @returns
 */
const TableSamplingRecord = React.forwardRef((props: any, ref: any) => {
    const { initialState } = useModel('@@initialState');
    const { dbname, sjnd } = initialState?.curPart as any;

    const curUser: API.CurUser = initialState?.curUser;

    const devGridRef = useRef<any>(null);
    const searchTextBoxRef = useRef<any>(null);
    //抽样表格数据
    const [dataGridData, setDataGridData] = useState<SampleReord[]>([]);
    const samplingRecordPopupRef = useRef<any>(null);
    const samplingSourcePopupRef = useRef<any>(null);
    const [searchValue, setSearchValue] = useState<string>();

    const [isNeedSamplingSourcePopup, setIsNeedSamplingSourcePopup] = useState<boolean>(false);
    const [isNeedSamplingRecordPopup, setIsNeedSamplingRecordPopup] = useState<boolean>(false);

    //刷新数据
    const refreshData = useCallback((inSearchValue?: string) => {
        inSearchValue = inSearchValue ?? searchValue;
        getSampleRecordList(dbname, '', inSearchValue, 0, consts.maxSampleCount)
            .then(dataGridData => {
                setDataGridData(dataGridData);
            })
    }, [dbname, searchValue])

    useEffect(() => {
        refreshData();
        if (ref) {
            ref.current = { refreshData }
        }
    }, [])
    /**
     * 编辑抽样记录
     * @param sampleRecord  为空时为新增加
     */
    function addOrEditSampleRecord(sampleRecordEditType: SampleRecordEditType, sampleRecord?: SampleReord) {

        addOrEditOrViewSampleRecord(
            sampleRecordEditType,
            dbname,
            samplingRecordPopupRef,// useRef<any>(null)
            curUser,
            dataGridData.length ? dataGridData : devGridRef.current.instance.getVisibleRows().map((item: any) => item.data),
            sjnd,
            sampleRecord,
            refreshData,
            setIsNeedSamplingRecordPopup,
        );

    }
    //编辑
    const onEditClick = (e: any) => {
        devGridRef.current.instance?.clearSelection();
        devGridRef.current.instance?.selectRows(e.row.data.guid, true)

        const sampleRecord: SampleReord = e.row.data;
        addOrEditSampleRecord(SampleRecordEditType.edit, sampleRecord);
    }
    //删除
    const onDelClick = (e: any) => {
        devGridRef.current.instance?.clearSelection();
        devGridRef.current.instance?.selectRows(e.row.data.guid, true)

        const sampleRecord: SampleReord = e.row.data;
        let itemNameStr = sampleRecord.itemName;
        if (sampleRecord.assertion) {
            itemNameStr += `-${getAssertionTexts(sampleRecord.assertion)}`
        }
        Modal.confirm({
            content: `确定要删除抽样记录:【${itemNameStr}】吗?`,
            onOk: async () => {

                let allSampleRecordTable = ''
                //取消抽样
                if (typeof (sampleRecord.sampleStepInfo) === 'object'
                    && sampleRecord.sampleStepInfo?.sampleParameterValues) {

                    if (! await updateTableIsChecked(sampleRecord.sampleStepInfo,
                        sampleRecord.sampleStepInfo?.sampleParameterValues, false, dbname)) {
                        return;
                    }

                    const projectOverallProps = sampleRecord.sampleStepInfo.projectOverallProps;
                    if (projectOverallProps?.curSampleTable?.tableName) {
                        allSampleRecordTable = getRealTableName_sampleList(projectOverallProps.curSampleTable.tableName,
                            { data_id: projectOverallProps.curDataId })
                    }
                }
                const retData = delSampleRecord(dbname, allSampleRecordTable, e.row.data.guid);
                refreshData();
            }
        });

    }
    /**
     * 重置滚动条
     */
    const resetScrollView = (devTableRef: any) => {
      const scrollView = devTableRef?.current?.instance?.getScrollable();
      devTableRef?.current?.instance?.repaint();
      if (scrollView) {
        scrollView.scrollTo({ left: 0, top: 0 });
      }
    };
    const sampleRecordDataGrid = useMemo(() => {

        // console.log(tempColumnsData, devBox, tableYearArr, dataGridData, '@@@');
        return (<div className={`componentTableListBox`} key={1} style={{ height: window.innerHeight * 0.9 }} >
            <DevGrid.RangeTap
                className={` PaperDevSortableGrid devHeadersCenter `}
                height={'100%'}
                width="100%"
                ref={devGridRef}
                dataSource={dataGridData}
                keyExpr="guid"
                defaultColumns={getSamplingRecordColumns({ onEditClick, onDelClick })}
                showBorders={true}
                showRowLines={true}
                showColumnLines={true}
                allowColumnResizing={true}
                isRemote={true}
                paging={{ enabled: false, }}
                loadPanel={{ enabled: true }}
                scrolling={{
                    mode: "virtual",
                    rowRenderingMode: "virtual",
                    renderAsync: true
                }}
                onCellDblClick={(e) => {
                    const { rowType, data, column } = e;
                    if (rowType === 'data') {
                        addOrEditSampleRecord(SampleRecordEditType.edit, data);
                        // console.log(e, data, column.dataField);
                    }
                }}
                columnMinWidth={50}
                sheetName={`抽样记录`}
                excelName={`抽样记录`}
                summary={{
                    totalItems: [
                        {
                            column: 'rn',
                            summaryType: 'count',
                            alignment: 'center',
                        },
                        {
                            column: consts.sampledAllSampleSizeField,
                            summaryType: 'sum',
                            alignment: 'center',

                        }]
                }}
            >
                <Selection mode="single" />

                <Toolbar>
                    <Item location="after" >

                        <Button
                            text="新增"
                            type='default'
                            onClick={() => {
                                //console.log("新增");
                                addOrEditSampleRecord(SampleRecordEditType.add
                                );//新增
                            }} />
                    </Item>
                    <Item location="after" >

                        <Button
                            text="样本源维护"
                            type='default'
                            onClick={() => {
                                // console.log("样本源维护");
                                setIsNeedSamplingSourcePopup(true);
                                //用一个定时器来显示pupop
                                const interval = setInterval(async () => {
                                    if (samplingSourcePopupRef.current) {
                                        clearInterval(interval);
                                        // const sampleTableList = await getSampleTableList(dbname)
                                        samplingSourcePopupRef.current.show({
                                            //sampleTableList,
                                            setIsNeedSamplingSourcePopup,
                                            updateSampleTableList: null,
                                        });
                                    }
                                }, 10)

                            }} />
                    </Item>{/*
                    <Item location="after" name="searchPanel"  /> */}
                    <Item location="after" widget='dxTextBox'

                        options={{
                            onInitialized: (e: any) => { searchTextBoxRef.current = e.component },
                            text: searchValue,
                            width: 130,
                            hint: '输入关键字搜索',
                            mode: 'search',
                            placeholder: '',
                            showClearButton: true,
                            onValueChanged: (e: any) => { setSearchValue(e.value) },
                            onFocusOut: (e: any) => {
                                const value = e.component._$textEditorInputContainer[0].childNodes[1].value
                                setSearchValue(value)
                            },
                            onEnterKey: async (e: any) => {
                                const value = e.component._$textEditorInputContainer[0].childNodes[1].value
                                setSearchValue(value);
                                resetScrollView(devGridRef);
                                refreshData(value)

                                setTimeout(() => {
                                    searchTextBoxRef.current?.focus();
                                }, 500);
                            },

                        }} />
                    <Item location="after">
                        <Button
                            icon='iconfont icon-refresh'
                            className='refreshButton_Style'
                            onClick={() => { refreshData(); }} />
                    </Item>
                    {/*   <Item location="after">
                        <Button
                            text="另存为"
                            onClick={() => {

                                downloadContent('Hello, World!', 'hello.txt');

                            }} />
                    </Item> */}

                </Toolbar>

            </DevGrid.RangeTap>
        </div >)
    }, [dataGridData]);

    return (<div>
        {sampleRecordDataGrid}
        {isNeedSamplingRecordPopup && <SamplingRecordPopup ref={samplingRecordPopupRef} />}
        {isNeedSamplingSourcePopup && <SamplingSourcePopup ref={samplingSourcePopupRef} />}
    </div>)
});


export default TableSamplingRecord;
